package com.pingan.haofang.searchcloud.batch.monitor;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;

import com.pingan.haofang.searchcloud.batch.common.Batch;
import com.pingan.haofang.searchcloud.monitor.service.DashboardIndexSummaryInfoService;

/**
 * 索引构建预警
 * 
 * @author yangbaohu662
 * @date 2018年10月31日
 * @since 1.0.0
 */

@Batch(value = "indexWarningTask", permanent = true)
@ConditionalOnProperty("indexWarningTask")
public class IndexWarningRunner {

    Logger LOG = LoggerFactory.getLogger(IndexWarningRunner.class);
    
    @Autowired
    private DashboardIndexSummaryInfoService indexSummaryInfoService;

    @Value("${api.warning.cron}")
    private String cron;

    /**
     * 任务刷新调度
     * 
     * @throws ParseException
     */
    @Scheduled(cron = "${index.warning.cron}")
    public void refresh() throws ParseException {
        
        LOG.info(new Date().toString());

        Date[] range = getRange(cron);

        indexSummaryInfoService.monitorIndexBuild(range[0], range[1]);

        LOG.info(new Date().toString());
    }

    private Date[] getRange(String cron) throws ParseException {

        // 默认用一天次数计算时间间隔
        Integer defaultBetweenDays = 1;

        CronExpression cronExpression = new CronExpression(cron);

        CronTrigger cronTrigger =
                TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();

        List<Date> dateList = TriggerUtils.computeFireTimesBetween((CronTriggerImpl) cronTrigger, null, new Date(),
                org.apache.commons.lang3.time.DateUtils.addDays(new Date(), defaultBetweenDays));

        Long between = 0L;
        if (CollectionUtils.isNotEmpty(dateList) && dateList.size() > 1) {
            between = (dateList.get(1).getTime() - dateList.get(0).getTime());
        }

        Date[] range = new Date[2];
        Date now = new Date();
        range[0] = DateUtils.addMilliseconds(new Date(), -between.intValue());
        range[1] = now;

        return range;
    }

}
